<template>
  <st-form-panel :title="title" v-loading="loading">
    <div slot="btm">
      <el-button type="primary" plain @click="$emit('list')">返 回</el-button>
      <el-button type="primary" plain @click="submitForm">保 存</el-button>
    </div>
    <div slot="content">
      <div class="container-top">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="合同名称:" prop="contractName">
                <el-input v-model="form.contractName" placeholder="请输入合同名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同类型:" prop="types">
                <el-select
                  v-model="form.types"
                  placeholder="请输入合同类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.contract_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人:" prop="contactsId">
                <el-input v-model="form.contactsName"
                          placeholder="请选择联系人"
                          readonly
                >
                  <el-button slot="append" @click="contactsSelect" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="8">
              <el-form-item label="商机:" prop="businessId">

                <el-input v-model="form.businessName"
                          placeholder="请选择商机" >
                  <el-button slot="append" @click="businessSelect" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下单日期:" prop="orderDate">
                <el-date-picker
                  v-model="form.orderDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请输入下单日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开始时间:" prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请输入开始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="结束时间:" prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请输入结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注：" prop="remark">
                <el-input v-model="form.remark" type="textarea"  placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="container-bottom">
        <el-row>
          <el-col :span="9">
            <el-button type="primary" @click="selectProduct">选择商品</el-button>
          </el-col >
          <el-col :span="15" style="font-size: 14px;
            text-align: right;">
            已添加产品: {{formData.dataList.length}}
            合计（元）：{{priceSum}}
            总折扣：<el-input style="width: 15%;" v-model="form.discountRate"></el-input>
            最终价格：<el-input style="width: 15%;" v-model="form.totalPrice"></el-input>
          </el-col>
        </el-row>

        <x-form ref="xForm" v-model="formData" :config="formConfig">
          <template #discount="scope">
            {{ (scope.row.salesPrice / scope.row.price).toFixed(2)}}
          </template>
          <template #subtotal="scope">
            {{scope.row.salesPrice * scope.row.num}}
          </template>
        </x-form>
      </div>
      <product-select ref="proSelect" @selected="productSelected"></product-select>
      <contacts-select ref="contactsSelectRef" @selected="contactsSelected"></contacts-select>
      <business-select ref="businessSelectRef" @selected="businessSelected"></business-select>
    </div>

  </st-form-panel>
</template>
<script>
import {getContract,addContract,updateContract,listContractProducts} from "@/api/crm/contract";

import productSelect from "@/views/crm/components/productSelect.vue";
import contactsSelect from '@/views/crm/components/contactsSelect.vue'
import businessSelect from '@/views/crm/components/businessSelect.vue'
export default {
  props:{
    customerForm:{
      type:Object,
      default:function() {
        return {};
      }
    }
  },
  components: {
    productSelect,
    contactsSelect,
    businessSelect
  },
  dicts:['contract_type'],
  data() {
    return {
      loading:0,
      form:{},
      rules:{},
      open:false,
      title:'',
      formData: {
        dataList: []
      },
      priceSum: 0,
      discountSum: 1,
      lastPrice:0,
      operateType:'add'
    }
  },
  watch:{
    'formData.dataList':{
      handler(newVal,oldVal){
        let salesPriceSum=0;
        let priceSum=1;
        this.formData.dataList.forEach((item)=>{
          salesPriceSum += item.salesPrice * item.num;
          priceSum=item.price * item.num;
        });
        console.log(salesPriceSum,priceSum);
        this.$set(this.form, 'discountRate',(salesPriceSum/priceSum).toFixed(2));
        this.$set(this.form, 'totalPrice',salesPriceSum);
        this.$set(this.form, 'money',priceSum);
        this.priceSum=salesPriceSum;
      },
      deep: true,
    },
  },
  computed: {
    formConfig() {
      const _this = this
      return {
        inline: false,
        item: [
          {
            xType: 'table',
            table:{
              label: '合同关联产品列表',
              name: 'dataList',
              height: 'calc(100vh - 525px)',
              size: 'mini',
              operate: {
                show: true,
                label: '操作',
                width: '80px',
                headerAlign: 'center',
                align: 'center',
                btn: [
                  {
                    type: 'text',
                    text:'删除',
                    icon: 'el-icon-delete',
                    size: 'mini',
                    circle: true,
                    style: '',
                    className: '',
                    click:(arr, index) => {
                      _this._handleItem(arr, index)
                    }
                  }
                ]
              },
              column: [
                {
                  label: '产品名称',
                  name: 'productName',
                  width: '150'
                },
                {
                  label: '单位',
                  name: 'unit',
                  width: '230'
                },
                {
                  label: '产品价格',
                  name: 'price'
                },
                {
                  label: '售价',
                  name: 'salesPrice',
                  xType: 'input',
                  rules: [{ required: true, message: '请输入售价', trigger: ['blur', 'change'] }]
                },
                {
                  label: '数量',
                  name: 'num',
                  xType:'inputNumber',
                  rules: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }]
                },
                {
                  label: '折扣',
                  name: 'discount',
                  slot:true,
                },
                {
                  label: '合计',
                  name: 'subtotal',
                  xType: 'input',
                  slot:true
                }
              ]
            }
          }
        ]
      }
    }
  },
  methods: {
    show(data){
      this.formData.dataList.splice(0,this.formData.dataList.length);
      if(typeof data === 'undefined' ){
        this.reset();
        this.title="新增合同";
      }else{
        this.reset();
        this.title="修改合同";
        this.loading++;
        getContract(data.contractId).then(res=>{
          this.form=res.data;
          this.loading--;
          res.data.productList.forEach((item)=>{
             this.$set(item,'num',parseInt(item.num,10));
             this.formData.dataList.push(item);
           })

        });
      }
    },
    contactsSelect(){
      this.$refs['contactsSelectRef'].show();
    },
    businessSelect(){
      this.$refs['businessSelectRef'].show();
    },
    selectProduct(){
      this.$refs.proSelect.show();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractName: null,
        money: null,
        customerId: null,
        contactsId: null,
        businessId: null,
        types: null,
        orderDate: null,
        startTime: null,
        endTime: null,
        checkStatus: null,
        examineRecordId: null,
        discountRate: null,
        totalPrice: null,
        paymentType: null,
        roUserId: null,
        rwUserId: null,
        remark: null,
        updatedBy: null,
        createdBy: null,
        ownerUserId: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    handleAdd(){
      this.reset();
      this.open=true;
      this.title="新增合同"
    },
    handleModify(contractId){
      this.reset();
      getContract(contractId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同";
      });
    },
    cancel(){
      this.open=false;
      this.$emit('reloadList')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$set(this.form,'productList',this.formData.dataList);
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$emit('list');
            });
          } else {
            this.$set(this.form,'customerId',this.customerForm.customerId);
            this.$set(this.form,'customerName',this.customerForm.customerName);
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit('list');
            });
          }
        }
      });
    },
    contactsSelected(items){
      this.$set(this.form,'contactsId',items.contactsId);
      this.$set(this.form,'contactsName',items.contactsName);
    },
    businessSelected(items){
      this.$set(this.form,'businessId',items.businessId);
      this.$set(this.form,'businessName',items.businessName);
    },
    productSelected(items){
      for (let i = 0; i < items.length; i++) {
        this.$set(items[i],'salesPrice',items[i].price);
        this.$set(items[i],'num', 1);
        this.formData.dataList.push(items[i]);
      }
    },
    getTableHeight() {
      let tableHeight
      const allPanel = document.querySelectorAll('.form-panel-container')
      allPanel.forEach(item => {
        let titleHeight=item.querySelectorAll('.form-title')
        const height = item.clientHeight
          -titleHeight[0].clientHeight
        if (height > 0) {
          tableHeight = height
        }
      })
      console.log(tableHeight)
      return tableHeight
    },

  }
}
</script>
<style scoped lang="scss">
.el-form{
  padding: 10px 0 0 0;
}
.el-date-editor{
  width:100%;
}
.el-select{
  width: 100%;
}
</style>
